<?php

/* 
 * Copyright 2015 gg.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Com\Wechat\ChatService;
/**
 * 对话服务-基础支持
 */
class BasicModel {
    /**
     * 获取微信的Token
     * @param type $appId
     * @param type $secret
     * @return srting/false 返回false代表参数错误，否则返回token
     */
    public static function getAccessToken($appId,$secret){
        S(array('type'=>C('DATA_CACHE_TYPE')));
        $token = S("wc_acToken".$appId);
        if (!$token){
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$secret";
            $curl = new \Com\Wechat\CurlModel();
            $request = $curl->curlSafeGet($url);
            $requestJson = json_decode($request);
            if (isset($requestJson->access_token)){
                S("wc_acToken".$appId,$requestJson->access_token,7000);
                return $requestJson->access_token;
            }else{
                return fales;
            }
        }else{
            return $token;
        }
    }
    /**
     * 验证来源
     * @param type $token
     * @param type $signature
     * @param type $timestamp
     * @param type $nonce
     * @return type
     */
    public function checkSignature($token,$signature,$timestamp,$nonce){
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = sha1(implode( $tmpArr ));
        return ($tmpStr == $signature);
    }
    /**
     * 获取微信服务器列表
     * @param type $token 微信accesstoken
     * @return false：获取列表错误，网络错误或token失效  array：服务器列表 
     */
    public function getWechatServerIp($token){
        $url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=$token";
        $curl = new \Com\Wechat\CurlModel();
        $result = json_decode($curl->curlSafeGet($url));
        if(isset($result->ip_list)){
            return ($result->ip_list);
        }else{
            return FALSE;
        }
    }
}
